package com.example.myapplication

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import android.util.Log

class LoginActivity : AppCompatActivity() {
    
    private lateinit var editTextUsername: EditText
    private lateinit var editTextPassword: EditText
    private lateinit var buttonLogin: Button
    private lateinit var buttonRegister: Button
    private lateinit var databaseHelper: DatabaseHelper
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        
        databaseHelper = DatabaseHelper(this)
        
        // 打印所有用户账号和密码到 Logcat
        databaseHelper.printAllUsers()
        
        initViews()
        setupListeners()
        
        // 自动启动WebSocket连接
        startAutoConnection()
    }
    
    /**
     * 自动启动WebSocket连接
     */
    private fun startAutoConnection() {
        try {
            // 获取WebSocket管理器实例
            val webSocketManager = com.example.myapplication.realtime.WebSocketManager.getInstance(this)
            
            // 检查是否有已保存的用户信息
            val prefs = getSharedPreferences("user_prefs", MODE_PRIVATE)
            val isLoggedIn = prefs.getBoolean("is_logged_in", false)
            
            if (isLoggedIn) {
                // 如果有已登录用户，恢复用户会话
                val userId = prefs.getLong("user_id", -1)
                val username = prefs.getString("username", "")
                val realName = prefs.getString("realName", "")
                val department = prefs.getString("department", "")
                val userTypeStr = prefs.getString("userType", "")
                
                if (userId != -1L && username != null && realName != null && department != null && userTypeStr != null) {
                    val user = User(
                        id = userId,
                        username = username,
                        password = "", // 不恢复密码
                        realName = realName,
                        department = department,
                        userType = UserType.valueOf(userTypeStr),
                        isApproved = true,
                        isActive = true
                    )
                    UserSession.currentUser = user
                    Log.d("LoginActivity", "恢复用户会话: ${user.realName}")
                }
            }
            
            // 尝试连接WebSocket
            Log.d("LoginActivity", "开始自动连接WebSocket服务器")
            webSocketManager.connect()
            
            // 显示连接状态
            Toast.makeText(this, "正在连接服务器...", Toast.LENGTH_SHORT).show()
            
        } catch (e: Exception) {
            Log.e("LoginActivity", "自动连接WebSocket失败", e)
            Toast.makeText(this, "连接服务器失败，请检查网络", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun initViews() {
        editTextUsername = findViewById(R.id.editTextUsername)
        editTextPassword = findViewById(R.id.editTextPassword)
        buttonLogin = findViewById(R.id.buttonLogin)
        buttonRegister = findViewById(R.id.buttonRegister)
    }
    
    private fun setupListeners() {
        buttonLogin.setOnClickListener {
            login()
        }
        buttonRegister.setOnClickListener {
            val intent = Intent(this, RegisterActivity::class.java)
            startActivity(intent)
        }
    }
    
    private fun login() {
        val username = editTextUsername.text.toString().trim()
        val password = editTextPassword.text.toString().trim()
        Log.d("LOGIN_DEBUG", "输入的用户名: '$username', 长度: ${username.length}")
        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "请输入用户名和密码", Toast.LENGTH_SHORT).show()
            return
        }
        try {
            // 先打印所有用户信息用于调试
            Log.d("LOGIN_DEBUG", "开始查找用户: $username")
            databaseHelper.printAllUsers()
            
            val user = databaseHelper.findUserByUsername(username)
            Log.d("LOGIN_DEBUG", "查找结果: ${if (user != null) "找到用户" else "未找到用户"}")
            
            if (user == null) {
                Toast.makeText(this, "用户名不存在", Toast.LENGTH_SHORT).show()
                return
            }
            Log.d("LOGIN_DEBUG", "输入的密码: '$password', 数据库密码: '${user.password}'")
            if (user.password != password) {
                Toast.makeText(this, "密码错误", Toast.LENGTH_SHORT).show()
                return
            }
            if (!user.isApproved) {
                Toast.makeText(this, "账号未审批，请等待管理员审核", Toast.LENGTH_SHORT).show()
                return
            }
            if (!user.isActive) {
                Toast.makeText(this, "账号已被停用", Toast.LENGTH_SHORT).show()
                return
            }
            // 登录成功，保存用户信息并跳转到主界面
            UserSession.currentUser = user
            // 新增：保存用户信息到SharedPreferences
            val prefs = getSharedPreferences("user_prefs", MODE_PRIVATE)
            prefs.edit()
                .putLong("user_id", user.id)
                .putString("username", user.username)
                .putString("realName", user.realName)
                .putString("department", user.department)
                .putString("userType", user.userType.name)
                .putBoolean("is_logged_in", true)
                .apply()
            Toast.makeText(this, "登录成功，欢迎 ${user.realName}！", Toast.LENGTH_SHORT).show()
            
            // 发送WebSocket认证消息
            try {
                val webSocketManager = com.example.myapplication.realtime.WebSocketManager.getInstance(this)
                webSocketManager.sendAuthMessageAfterLogin()
                Log.d("LoginActivity", "WebSocket认证消息发送成功")
            } catch (e: Exception) {
                Log.e("LoginActivity", "发送WebSocket认证消息失败", e)
            }
            
            // 启动实时通信服务
            try {
                com.example.myapplication.realtime.RealtimeService.startService(this)
                Log.d("LoginActivity", "实时通信服务启动成功")
            } catch (e: Exception) {
                Log.e("LoginActivity", "启动实时通信服务失败", e)
                // 即使服务启动失败，也不影响登录流程
                Toast.makeText(this, "实时通信服务启动失败，但登录成功", Toast.LENGTH_SHORT).show()
            }
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            finish()
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e("LOGIN_DEBUG", "登录异常", e)
            Toast.makeText(this, "登录异常: ${e.javaClass.simpleName}: ${e.message}", Toast.LENGTH_LONG).show()
        }
    }
}